package com.webserver.core;

import com.webserver.http.HttpServletRequest;

import java.io.*;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class ClientHandler implements Runnable{
    private Socket socket;

    public ClientHandler(Socket socket){
        this.socket=socket;
    }
    @Override
    public void run() {
        try {
            HttpServletRequest request=new HttpServletRequest(socket);

            String path=request.getUri();

            File file=new File("./webapps/myweb"+path);
            OutputStream out=socket.getOutputStream();
            String line="HTTP/1.1 200 OK";
            byte[] data=line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);
            out.write(10);

            line="Content-Type: text/html";
            data=line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);
            out.write(10);

            line="Content-Length:"+file.length();
            data=line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);
            out.write(10);

            out.write(13);
            out.write(10);

            FileInputStream fis=new FileInputStream(file);
            int len;
            byte[] buf=new byte[1024*10];
            while ((len=fis.read(buf))!=-1){
                out.write(buf,0,len);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
